package com.mairuide.casemanage.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.utils.IdWorker;
import com.mairuide._frame.utils.UpdateTool;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.DealFlowService;
import com.mairuide.bill.information.PersonInformation;
import com.mairuide.bill.information.PersonInformationParams;
import com.mairuide.bill.information.PersonInformationService;
import com.mairuide.casemanage.pojo.CaseManage;
import com.mairuide.casemanage.pojo.CaseManageParams;
import com.mairuide.casemanage.service.CaseManageService;
import com.mairuide.datalog.ActionType;
import com.mairuide.datalog.DataOperationImportLog;
import com.mairuide.datalog.DataOperationImportLogService;
import com.mairuide.datalog.DataOperationImportParams;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.datalog.ModuleFlag;
import com.mairuide.datalog.SystemFlag;
import com.mairuide.entity.PageResult;
import com.mairuide.entity.Result;
import com.mairuide.entity.StatusCode;
import com.mairuide.menuinfo.MenuInfo;
import com.mairuide.openaccountinfo.service.OpenaccountInfoService;
import com.mairuide.phone.PhoneRecord;
import com.mairuide.phone.import_phone.PhoneRecordingService;
import com.mairuide.platmanager.PlatManager;
import com.mairuide.platmanager.PlatManagerService;

/**
 * 控制器层
 * @author Administrator
 *
 */
@Controller
@CrossOrigin
@RequestMapping("/casemanage")
public class CaseManageController extends BaseController {

	@Autowired
	private CaseManageService caseService;

	@Autowired
	private IdWorker idWorker;

	@Resource
	private DataOperationLogService dataOperationLogService;
	
	@Resource
	private DealFlowService dealFlowService;

	@Autowired
	private OpenaccountInfoService openaccountInfoService;
	
	@Autowired
	private DataOperationImportLogService dataOperationImportLogService;
	
	@Autowired
	private PlatManagerService platManagerService;
	
	@Autowired
	private PersonInformationService personInformationService;
	
	@Autowired
    private PhoneRecordingService phoneRecordingService;
	
	@ModuleCode("billother")
    @RequestMapping(method= RequestMethod.GET,value = "casemanageInit")
    public Object monthAnalysisSingle(ModelMap model){
        return "/casemanage/casemanage";
    }
	
	@ModuleCode("caseObject")
	@RequestMapping(method= RequestMethod.GET,value = "casemanageObject")
	public Object casemanageObject(ModelMap model){
		return "/casemanage/casemanageObject/casemanageObject";
	}
	
	@RequestMapping(method= RequestMethod.GET,value = "showBillImport")
	public Object showZdImport(ModelMap model){
		return "/casemanage/showBillImport";
	}
	
	@RequestMapping(method= RequestMethod.GET,value = "setCaseUuid")
	@ResponseBody
	public Object setCaseUuid(String caseUuid,HttpServletRequest request){
		if(com.mairuide._frame.utils.StringUtils.isNotEmpty(caseUuid)) {
			request.getSession().setAttribute("caseId", caseUuid);
		}
		return new HashMap<>().put("success","200");
	}
	@RequestMapping(value = "/showPhoneImport", method = RequestMethod.GET)
    public Object importFile(ModelMap model) {
        return "/casemanage/showPhoneImport";
    }
	
	@RequestMapping(method= RequestMethod.GET,value = "caseManagePanel")
	public Object caseManagePanel(ModelMap model){
		return "/casemanage/caseManagerDialog";
	}
	
	@RequestMapping(method= RequestMethod.GET,value = "showCaseManageDetail")
	public Object showCaseManageDetail(ModelMap model){
		return "/casemanage/caseManagerDetailDialog";
	}
	
	@RequestMapping(method= RequestMethod.GET,value = "showDealFlowDetail")
	public Object showDealFlowDetail(ModelMap model){
		return "/casemanage/showDealFlowDetailDialog";
	}
	
	@RequestMapping(method= RequestMethod.GET,value = "showPhoneDetail")
	public Object showPhoneDetail(ModelMap model){
		return "/casemanage/showPhoneDetailDialog";
	}
	
	@RequestMapping(method= RequestMethod.GET,value = "showCaseManageObjectDetail")
	public Object showCaseManageObjectDetail(ModelMap model){
		return "/casemanage/casemanageObject/caseObjectEditDialog";
	}
	
	@RequestMapping(method= RequestMethod.GET,value = "showCaseObjectBillMapping")
	public Object showCaseObjectMapping(ModelMap model){
		return "/casemanage/casemanageObject/showCaseObjectBillMapping";
	}
	
	@RequestMapping(method= RequestMethod.GET,value = "showCaseObjectPhoneMapping")
	public Object showCaseObjectPhoneMapping(ModelMap model){
		return "/casemanage/casemanageObject/showCaseObjectPhoneMapping";
	}
	
	/**
	 * 查询全部数据
	 * @return
	 */
	@RequestMapping(method= RequestMethod.GET,value = "list")
	public Object findAll(ModelMap model,String menuCode,String menuCode2){
		model.addAttribute("menuCode",menuCode==null?"":menuCode);
		model.addAttribute("menuCode2",menuCode2==null?"":menuCode2);
		return "/casemanage/list";
	}
	
	/**
	 * 根据ID查询
	 * @param id ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/{id}",method= RequestMethod.GET)
	public Result findById(@PathVariable Integer id,ModelMap model){
		return new Result(true,StatusCode.OK,"查询成功",caseService.findById(id));
	}


	/**
	 * 分页+多条件查询
	 * @param searchMap 查询条件封装
	 * @param page 页码
	 * @param size 页大小
	 * @return 分页结果
	 */
	@ResponseBody
	@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
	public Result findSearch(@RequestBody(required = false) Map searchMap , @PathVariable int page, @PathVariable int size){
 		Page<CaseManage> pageList = caseService.findSearch(searchMap, page, size,super.getLoginUser().getId());
		return  new Result(true, StatusCode.OK,"查询成功",  new PageResult<CaseManage>(pageList.getTotalElements(), pageList.getContent()) );
	}

	/**
          * 根据条件查询
     * @param searchMap
     * @return
     */
	@ResponseBody
    @RequestMapping(value="/findCaseManageListByPage",method = RequestMethod.POST)
    public Object findCaseManageListByPage(String keyword,Integer page,Integer rows,String sort,String order){
		PageResult<CaseManage> pr = caseService.findCaseManageByPage(keyword, page, rows, super.getLoginUser().getId(),sort,order);
		Map<String, Object> result = new HashMap<String,Object>();
		result.put("total", pr.getTotal());
		result.put("rows", pr.getRows());
		return result;
    }
	
	/**
	  * 根据条件查询案件对象
    * @param searchMap
    * @return
    */
	@ResponseBody
    @RequestMapping(value="/findPersonInformationByPage",method = RequestMethod.POST)
    public Object findPersonInformationByPage(PersonInformationParams pp){
		Map<String, Object> result = new HashMap<String,Object>();
		PageResult<PersonInformation> pr = personInformationService.findPersonInformationByPage(pp);
		result.put("total", pr.getTotal());
		result.put("rows", pr.getRows());
		return result;
    }
	
	/**
	 * 查询证件类型下拉菜单
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value="/findIdType",method = RequestMethod.GET)
	public List<String> findIdType(){
		return personInformationService.findIdType();
	}
	
	/**
	 * 查询证件类型下拉菜单MAP
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value="/findIdTypeMap",method = RequestMethod.GET)
	public List<Map<String,String>> findIdTypeMap(){
		List<Map<String,String>> result = new ArrayList<>();
		List<String> rs = personInformationService.findIdType();
		if(null != rs && !rs.isEmpty()) {
			for(String r :rs) {
				Map<String,String> e = new HashMap<>();
				e.put("text", r);
				e.put("value", r);
				result.add(e);
			}
		}
		return result;
	}
	
	/**
	  * 根据条件查询
     * @param searchMap
     * @return
     */
	@ResponseBody
    @RequestMapping(value="/findDataOperationImportLogByPage",method = RequestMethod.POST)
    public Object findDataOperationImportLogByPage(DataOperationImportParams opip){
		Map<String, Object> result = new HashMap<String,Object>();
		PageResult<DataOperationImportLog> pr = dataOperationImportLogService.findDataOperationImportLogByPage(opip);
		if(null != pr.getRows() && pr.getRows().size() > 0) {
			for(DataOperationImportLog d : pr.getRows()) {
				PlatManager p = platManagerService.findOne(d.getUserId());
				d.setUserName(p.getNickName());
			}
		}
		result.put("total", pr.getTotal());
		result.put("rows", pr.getRows());
		return result;
    }
	
	/**
	 * 增加
	 * @param case
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "addCase")
	public Result add(CaseManageParams caseManageParams) throws Exception{
		CaseManage cm = new CaseManage();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//插入新增案件
		long l = idWorker.nextId();
		if (com.mairuide._frame.utils.StringUtils.isEmpty(caseManageParams.getCase_time())){
			cm.setCase_time(new Date());
		}else {
			cm.setCase_time(sdf.parse(caseManageParams.getCase_time()));
		}
		cm.setCase_name(caseManageParams.getCase_name());
		cm.setCase_region(caseManageParams.getCase_region());
		cm.setCase_type(caseManageParams.getCase_type());
		cm.setPerson_type(caseManageParams.getPerson_type());
		cm.setCase_victim(caseManageParams.getCase_victim());
		cm.setCase_authority(caseManageParams.getCase_authority());
		cm.setCase_uuid(String.valueOf(l));
		cm.setCreate_time(new Date());
		cm.setCase_remark(caseManageParams.getCase_remark());
		cm.setCreate_id(super.getLoginUser().getId());
		cm.setWhich_table(1);
		caseService.add(cm);
		//插入新建的表，表名是案件id
		caseService.createTable(l);
		//插入新增日志
		dataOperationLogService.save(null, super.getLoginUser(), cm, new CaseManage(), SystemFlag.ZD, ModuleFlag.CASEMANAGER, ActionType.ADD);
		return new Result(true,StatusCode.OK,"增加成功",cm);
	}
	
	/**
	 * 修改
	 * @param case
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value="/updateCase")
	public Result update(CaseManageParams caseManageParams, Integer id) throws Exception{
		CaseManage cm = new CaseManage();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (com.mairuide._frame.utils.StringUtils.isEmpty(caseManageParams.getCase_time())){
			cm.setCase_time(new Date());
		}else {
			cm.setCase_time(sdf.parse(caseManageParams.getCase_time()));
		}
		cm.setCase_name(caseManageParams.getCase_name());
		cm.setCase_region(caseManageParams.getCase_region());
		cm.setCase_type(caseManageParams.getCase_type());
		cm.setPerson_type(caseManageParams.getPerson_type());
		cm.setCase_victim(caseManageParams.getCase_victim());
		cm.setCase_authority(caseManageParams.getCase_authority());
		cm.setCase_remark(caseManageParams.getCase_remark());
		cm.setId(id);
		
		CaseManage caseManage1 = caseService.findById(id);
		UpdateTool.copyNullProperties(caseManage1,cm);
		caseService.update(cm);
		//插入更新日志
		dataOperationLogService.save(id.toString(), super.getLoginUser(), caseManage1, cm, SystemFlag.ZD, ModuleFlag.CASEMANAGER, ActionType.MODIFY);
		return new Result(true,StatusCode.OK,"修改成功");
	}
	
	/**
	 * 删除
	 * @param id
	 * @throws Exception 
	 */
	@RequestMapping(value="/delete")
	@ResponseBody
	public Result delete(Integer id) throws Exception{
		CaseManage cm = caseService.findById(id);

		openaccountInfoService.deleteByCasemanageId(cm.getCase_uuid());
		//删除该案件下所有数据
		String whichTable = caseService.getWhichTable(cm.getCase_uuid());
		if ("tb_deal_flow".equals(whichTable)){

			dealFlowService.deleteByCasemanageId(cm.getCase_uuid());
		}else {
			//删除该案件对应的表
			caseService.delTable(cm.getCase_uuid());
		}
		
		caseService.deleteById(id);
		//删除自定义导入临时表
		caseService.deleteTempTable(cm.getCase_uuid());
		//删除导入文件表信息
		dataOperationImportLogService.deleteByCaseManagerId(cm.getCase_uuid());
		//删除人员基础信息
		personInformationService.deleteByCasemanagerId(cm.getCase_uuid());
		//删除话单信息
		phoneRecordingService.deleteByCasemanageId(cm.getCase_uuid());
		//判断是否在正在执行的案件，如果是，就把session中的caseid置空
		String caseId = (String) request.getSession().getAttribute("caseId");
		if (cm.getCase_uuid().equals(caseId)){
			request.getSession().removeAttribute("caseId");
		}
		//插入删除日志
		dataOperationLogService.save(id.toString(), super.getLoginUser(), cm, cm, SystemFlag.ZD, ModuleFlag.CASEMANAGER, ActionType.DELETE);
		return new Result(true,StatusCode.OK,"删除成功");
	}
	
	/**
	 * 查询列表根据权限和创建人
	 * @param id
	 */
	@RequestMapping(value="/uuid",method= RequestMethod.GET)
	@ResponseBody
	public Result getCaseuuidList(){
		List<CaseManage> list = caseService.getCaseuuidList(0, super.getLoginUser().getId());
		return new Result(true,StatusCode.OK,"查询成功",list);
	}
	
	/**
	 * 切换案件
	 * @param id
	 */
	@RequestMapping(value="/choose")
	@ResponseBody
	public Result choose(HttpServletRequest request,@RequestParam(required=true) String caseId){
		if(StringUtils.isNotEmpty(caseId)){
			request.getSession().setAttribute("caseId", caseId);
		}
		List<MenuInfo> firstLevelMenuList = (List<MenuInfo>)request.getSession().getAttribute("firstLevelMenuList");
		List<String> collect = firstLevelMenuList.stream().map(m -> m.getMenuName()).collect(Collectors.toList());
		Map<String, List<MenuInfo>> secondLevelMenuMap = (Map<String, List<MenuInfo>>)request.getSession().getAttribute("secondLevelMenuMap");

		String s="";
		if (collect.contains("账单系统")){
			MenuInfo bill = firstLevelMenuList.get(collect.indexOf("账单系统"));
			List<MenuInfo> menuInfos = secondLevelMenuMap.get(String.valueOf(bill.getMenuId()));
			if(menuInfos!=null&&menuInfos.size()>0){
				s = menuInfos.get(0).getMenuUrl();
			}
		}else if (collect.contains("话单系统")){
			MenuInfo bill = firstLevelMenuList.get(collect.indexOf("话单系统"));
			List<MenuInfo> menuInfos = secondLevelMenuMap.get(String.valueOf(bill.getMenuId()));
			if(menuInfos!=null&&menuInfos.size()>0){
				s = menuInfos.get(0).getMenuUrl();
			}
		}else if (collect.contains("系统设置")){
			MenuInfo bill = firstLevelMenuList.get(collect.indexOf("系统设置"));
			List<MenuInfo> menuInfos = secondLevelMenuMap.get(String.valueOf(bill.getMenuId()));
			if(menuInfos!=null&&menuInfos.size()>0){
				s = menuInfos.get(0).getMenuUrl();
			}
		}else{
			s="";
		}
		return new Result(true,StatusCode.OK,"",s);
	}
	
	/**
          * 编辑人员详情
     * @param paramsMap
     * @return
     */
    @ResponseBody
    @RequestMapping(method= RequestMethod.POST,value = "/editPersonInformation")
    public Object editPersonInformation(@RequestBody PersonInformationParams pip){
    	//通过姓名身份证判断修改的数据是否存在，如果存在则标识将该对象下的所有卡归属到新对象下
    	PersonInformation pi = personInformationService.findByPersonNameAndIdNumber(pip.getPersonName(), pip.getIdNumber());
    	if(null != pi && pi.getPId() != pip.getpId() && !pi.getPId().equals(pip.getpId())) {
    		pi.setIdType(pip.getIdType());
			pi.setPhoneNumber(pip.getPhoneNumber());
			pi.setBirthPlace(pip.getBirthPlace());
			pi.setBodyType(pip.getBodyType());
			pi.setRemark(pip.getRemark());
			pi.setDataSource("案件对象编辑");
			personInformationService.save(pi);
			if(pip.getpId() != null) {
				personInformationService.delete(pip.getpId());
			}
			List<String> cards = personInformationService.findAccountBodyCardsByAccountBoydAndIdNumber(pip.getOldPersonName(), pip.getOldIdNumber(), pip.getCasemanagerId());
			//该主题下存在卡号集合则更新所有卡号到新主体下，如果不存在卡号则更新交易主体、证件号码
			if(cards != null && cards.size() > 0) {
				dealFlowService.findByAccountBodyCardAndCasemanageId(cards, pip.getCasemanagerId(),pip.getPersonName(),pip.getIdNumber(),pip.getBodyType());
			}else {
    			dealFlowService.findByAccountBodyAndCasemanageId(pip.getOldPersonName(), pip.getCasemanagerId(),pip.getPersonName(),pip.getIdNumber(),pip.getBodyType());
			}
    	}else {
    		PersonInformation pp = null;
    		if(null != pip.getpId()) {
    			pp = personInformationService.findOne(pip.getpId());
    			if(pp != null) {
        			if(!pp.getPersonName().equals(pip.getPersonName()) || !pp.getIdNumber().equals(pip.getIdNumber())) {
            			dealFlowService.findByAccountBodyAndCasemanageId(pip.getOldPersonName(), pip.getCasemanagerId(),pip.getPersonName(),pip.getIdNumber(),pip.getBodyType());
        			}
        			pp.setPersonName(pip.getPersonName());
        			pp.setIdType(pip.getIdType());
        			pp.setIdNumber(pip.getIdNumber());
        			pp.setPhoneNumber(pip.getPhoneNumber());
        			pp.setBirthPlace(pip.getBirthPlace());
        			pi.setBodyType(pip.getBodyType());
        			pp.setRemark(pip.getRemark());
        			pp.setDataSource("案件对象编辑");
        			personInformationService.save(pp);
        		}else {
        			PersonInformation p = new PersonInformation();
            		p.setPersonName(pip.getPersonName());
            		p.setIdType(pip.getIdType());
        			p.setIdNumber(pip.getIdNumber());
        			p.setPhoneNumber(pip.getPhoneNumber());
        			p.setBirthPlace(pip.getBirthPlace());
        			pi.setBodyType(pip.getBodyType());
        			p.setRemark(pip.getRemark());
        			p.setCasemanagerId(pip.getCasemanagerId());
        			p.setDataSource("案件对象新增");
            		personInformationService.save(p);
        		}
    		}else {
    			if(!pip.getPersonName().equals(pip.getOldPersonName())) {
    	    		dealFlowService.findByAccountBodyAndCasemanageId(pip.getOldPersonName(), pip.getCasemanagerId(),pip.getPersonName(),pip.getIdNumber(),pip.getBodyType());
    			}
    			PersonInformation p = new PersonInformation();
        		p.setPersonName(pip.getPersonName());
        		p.setIdType(pip.getIdType());
    			p.setIdNumber(pip.getIdNumber());
    			p.setPhoneNumber(pip.getPhoneNumber());
    			p.setBirthPlace(pip.getBirthPlace());
    			pi.setBodyType(pip.getBodyType());
    			p.setRemark(pip.getRemark());
    			p.setCasemanagerId(pip.getCasemanagerId());
    			p.setDataSource("案件对象新增");
        		personInformationService.save(p);
    		}
    		
    	}
    	//判断修改的手机号码不为空并且存在话单则更新话单的身份证信息和主叫号码姓名
    	if(StringUtils.isNotEmpty(pip.getPhoneNumber())) {
    		List<PhoneRecord> pr = phoneRecordingService.findByServiceNumberAndCasemanageIdAndIsDelete(pip.getPhoneNumber(), pip.getCasemanagerId(), 0);
    		if(pr != null) {
    			for(PhoneRecord p : pr) {
    				p.setIdNumber(pip.getIdNumber());
    				p.setServiceUserInformation(pip.getPersonName());
    				phoneRecordingService.save(p);
    			}
    		}
    	}
		return SUCCESS();
    }
    
    /**
	 * 删除
	 * @param id
	 * @throws Exception 
	 */
	@RequestMapping(value="/deleteCaseObject")
	@ResponseBody
	public Result deleteCaseObject(Integer id) throws Exception{
		if(null != id) {
			PersonInformation pip = personInformationService.findOne(id);
			List<String> cards = personInformationService.findAccountBodyCardsByAccountBoydAndIdNumber(pip.getPersonName(), pip.getIdNumber(), pip.getCasemanagerId());
			if(null != cards && cards.size() > 0) {
				personInformationService.deleteDealFlowsByAccountBodyCard(cards, pip.getCasemanagerId());
			}
			personInformationService.delete(id);
			return new Result(true,StatusCode.OK,"删除成功");
		}
		return new Result(false,StatusCode.ERROR,"删除失败");
	}
	
	/**
	 * 查询导入账单文件下所有未关联上的案件对象
	 * @param id
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/findCaseObjectBillMapping",method = RequestMethod.POST)
	public Object findCaseObjectMapping(PersonInformationParams pp) throws Exception{
		Map<String, Object> result = new HashMap<String,Object>();
		if(StringUtils.isNotEmpty(pp.getFileUuids())) {
			PageResult<DealFlow> page = personInformationService.findCaseObjectMapping(pp);
			result.put("total", page.getTotal());
			result.put("rows", page.getRows());
		}
		return result;
	}
	
	/**
	 * 查询导入话单文件下所有未关联上的案件对象
	 * @param id
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value = "/findCaseObjectPhoneMapping",method = RequestMethod.POST)
	public Object findCaseObjectPhoneMapping(PersonInformationParams pp) throws Exception{
		Map<String, Object> result = new HashMap<String,Object>();
		if(StringUtils.isNotEmpty(pp.getFileUuids())) {
			PageResult<PhoneRecord> page = personInformationService.findCaseObjectPhoneMapping(pp);
			result.put("total", page.getTotal());
			result.put("rows", page.getRows());
		}
		return result;
	}
	
	/**
     * 编辑账单案件对象
	 * @param paramsMap
	 * @return
	 */
	@ResponseBody
	@RequestMapping(method= RequestMethod.POST,value = "/saveCaseObject4Bill")
	public Object saveCaseObject4Bill(@RequestBody PersonInformationParams pip){
		personInformationService.updateCaseObjectBillMapping(pip);
		return SUCCESS();
	}
	
	/**
     * 编辑话单案件对象
	 * @param paramsMap
	 * @return
	 */
	@ResponseBody
	@RequestMapping(method= RequestMethod.POST,value = "/saveCaseObject4Phone")
	public Object saveCaseObject4Phone(@RequestBody PersonInformationParams pip){
		personInformationService.updateCaseObjectPhoneMapping(pip);
		return SUCCESS();
	}
}
